package com.campus.runrun.controller;

import com.campus.runrun.common.utils.OSSClientUtil;
import com.campus.runrun.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/api/upload")
@Api(tags = "文件上传模块")
public class UploadController {

    @Autowired
    private OSSClientUtil ossClientUtil;

    @ApiOperation(value = "上传单图片", notes = "回传单张图片url外链，例如：http://we-market.oss-cn-beijing.aliyuncs.com/goods/1587806330397.jpg")
    @PostMapping("/singlePhotoUpload")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(value = "校验token", name = "Authorization", paramType = "header", required = true)
    })
    public R singlePhotoUpload(@RequestParam("file") MultipartFile file) {
        boolean checkRes = checkPicType(file);
        if (!checkRes) {
            // 如果验证未通过
            return R.error("请选择.jpg/.JPG/.jpeg/.JPEG/.png/.PNG图片文件");
        }
        //获取单图片路径
        String imageUrl = ossClientUtil.checkImage(file);  //image 为MultipartFile类型
        return R.ok().put("imageUrl", imageUrl);
    }

    @ApiOperation(value = "多图片上传", notes = "回传多张图片url外链 array数组")
    @PostMapping("/photosUpload")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(value = "校验token", name = "Authorization", paramType = "header", required = true)
    })
    public R photosUpload(@RequestParam("fileList") List<MultipartFile> fileList) {
        for (MultipartFile file : fileList) {
            boolean checkRes = checkPicType(file);
            if (!checkRes) {
                // 如果验证未通过
                return R.error("请选择.jpg/.JPG/.jpeg/.JPEG/.png/.PNG图片文件");
            }
        }
        List<String> photoUrlList = new ArrayList<>();
        for (MultipartFile file : fileList) {
            //获取单图片路径
            String imageUrl = ossClientUtil.checkImage(file);  //image 为MultipartFile类型
            photoUrlList.add(imageUrl);
        }
        return R.ok().put("data", photoUrlList);
    }

    private boolean checkPicType(MultipartFile file) {
        String picType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        return "jpg".equals(picType) || "JPG".equals(picType) || "jpeg".equals(picType) || "JPEG".equals(picType) || "png".equals(picType) || "PNG".equals(picType);
    }
}
